<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>音频播放测试 - Android WebView</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }

        h1 {
            color: #667eea;
            margin-bottom: 8px;
            font-size: 24px;
        }

        .subtitle {
            color: #666;
            margin-bottom: 24px;
            font-size: 14px;
        }

        .input-group {
            margin-bottom: 16px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
        }

        .button-group {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }

        button {
            flex: 1;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #f5f5f5;
            color: #333;
        }

        .btn-secondary:hover {
            background: #e0e0e0;
        }

        .log-container {
            margin-top: 24px;
            padding: 16px;
            background: #f8f9fa;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.6;
        }

        .log-entry {
            margin-bottom: 4px;
            padding: 4px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .log-info {
            color: #2196F3;
        }

        .log-success {
            color: #4CAF50;
        }

        .log-error {
            color: #f44336;
        }

        .log-warning {
            color: #FF9800;
        }

        .audio-container {
            margin-top: 20px;
            padding: 16px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        audio {
            width: 100%;
            margin-top: 12px;
        }

        .status {
            padding: 12px;
            border-radius: 8px;
            margin-top: 16px;
            font-size: 14px;
        }

        .status.info {
            background: #e3f2fd;
            color: #1976d2;
        }

        .status.success {
            background: #e8f5e9;
            color: #388e3c;
        }

        .status.error {
            background: #ffebee;
            color: #c62828;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎵 音频播放测试</h1>
        <p class="subtitle">在 Android WebView 中测试音频流播放</p>

        <div class="input-group">
            <label for="streamUrl">流链接 URL:</label>
            <input type="text" id="streamUrl" placeholder="输入音频流链接..." value="">
        </div>

        <div class="input-group">
            <label for="mimeType">MIME 类型:</label>
            <input type="text" id="mimeType" placeholder="例如: video/mp4; codecs=&quot;avc1.42001E, mp4a.40.2&quot;" 
                   value='video/mp4; codecs="avc1.42001E, mp4a.40.2"'>
        </div>

        <div class="button-group">
            <button class="btn-primary" onclick="startTest()">开始测试</button>
            <button class="btn-secondary" onclick="clearLog()">清空日志</button>
        </div>

        <div id="status" class="status info" style="display: none;"></div>

        <div id="audioContainer" class="audio-container" style="display: none;">
            <strong>音频播放器:</strong>
            <div id="audioElement"></div>
        </div>

        <div class="log-container" id="logContainer">
            <div class="log-entry log-info">等待开始测试...</div>
        </div>
    </div>

    <script>
        // 日志系统
        const logContainer = document.getElementById('logContainer');
        let audioInstance = null;

        function addLog(message, type = 'info') {
            const entry = document.createElement('div');
            entry.className = `log-entry log-${type}`;
            const timestamp = new Date().toLocaleTimeString();
            entry.textContent = `[${timestamp}] ${message}`;
            logContainer.appendChild(entry);
            logContainer.scrollTop = logContainer.scrollHeight;
            console.log(message);
        }

        function clearLog() {
            logContainer.innerHTML = '<div class="log-entry log-info">日志已清空</div>';
        }

        function showStatus(message, type = 'info') {
            const statusDiv = document.getElementById('status');
            statusDiv.className = `status ${type}`;
            statusDiv.textContent = message;
            statusDiv.style.display = 'block';
        }

        // 重写 console.log 以显示在页面上
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;

        console.log = function(...args) {
            originalLog.apply(console, args);
            addLog(args.join(' '), 'info');
        };

        console.error = function(...args) {
            originalError.apply(console, args);
            addLog(args.join(' '), 'error');
        };

        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addLog(args.join(' '), 'warning');
        };

        // 音频测试函数（从 audio_test_console.js 复制）
        function testAudioWithAudioElement(streamUrl, mimeType) {
            addLog('开始测试音频播放...', 'info');
            addLog('流链接: ' + streamUrl, 'info');
            addLog('MIME 类型: ' + mimeType, 'info');
            
            // 创建 Audio 元素
            const audio = new Audio();
            
            // 设置音频源
            audio.src = streamUrl;
            
            // 设置 MIME 类型（如果浏览器支持）
            if (mimeType) {
                audio.type = mimeType;
            }
            
            // 添加事件监听器
            audio.addEventListener('loadstart', () => {
                addLog('✓ 开始加载音频', 'success');
            });
            
            audio.addEventListener('loadedmetadata', () => {
                addLog('✓ 音频元数据已加载', 'success');
                addLog('  时长: ' + audio.duration + ' 秒', 'info');
            });
            
            audio.addEventListener('loadeddata', () => {
                addLog('✓ 音频数据已加载', 'success');
            });
            
            audio.addEventListener('canplay', () => {
                addLog('✓ 音频可以播放', 'success');
                showStatus('音频已准备好，可以播放', 'success');
            });
            
            audio.addEventListener('canplaythrough', () => {
                addLog('✓ 音频可以流畅播放', 'success');
            });
            
            audio.addEventListener('play', () => {
                addLog('▶ 开始播放', 'success');
                showStatus('正在播放...', 'success');
            });
            
            audio.addEventListener('pause', () => {
                addLog('⏸ 暂停播放', 'info');
                showStatus('已暂停', 'info');
            });
            
            audio.addEventListener('ended', () => {
                addLog('■ 播放结束', 'info');
                showStatus('播放结束', 'info');
            });
            
            audio.addEventListener('error', (e) => {
                addLog('✗ 播放错误: ' + e, 'error');
                if (audio.error) {
                    addLog('错误代码: ' + audio.error.code, 'error');
                    addLog('错误消息: ' + audio.error.message, 'error');
                }
                showStatus('播放出错: ' + (audio.error ? audio.error.message : '未知错误'), 'error');
            });
            
            audio.addEventListener('timeupdate', () => {
                // 每5秒打印一次进度（避免日志过多）
                if (Math.floor(audio.currentTime) % 5 === 0) {
                    const current = Math.floor(audio.currentTime);
                    const total = Math.floor(audio.duration) || 0;
                    addLog('播放进度: ' + current + ' / ' + total + ' 秒', 'info');
                }
            });
            
            // 将音频元素添加到页面
            audio.controls = true;
            audio.style.width = '100%';
            const audioContainer = document.getElementById('audioContainer');
            const audioElementDiv = document.getElementById('audioElement');
            audioElementDiv.innerHTML = '';
            audioElementDiv.appendChild(audio);
            audioContainer.style.display = 'block';
            
            // 尝试播放
            audio.play().then(() => {
                addLog('✓ 播放成功', 'success');
            }).catch((error) => {
                addLog('✗ 播放失败: ' + error.message, 'error');
                showStatus('播放失败: ' + error.message, 'error');
            });
            
            return audio;
        }

        function testAudioWithVideoElement(streamUrl, mimeType) {
            addLog('开始测试音频播放（使用 Video 元素）...', 'info');
            addLog('流链接: ' + streamUrl, 'info');
            addLog('MIME 类型: ' + mimeType, 'info');
            
            const video = document.createElement('video');
            video.src = streamUrl;
            
            if (mimeType) {
                video.type = mimeType;
            }
            
            video.style.display = 'none';
            video.controls = true;
            
            video.addEventListener('loadstart', () => {
                addLog('✓ 开始加载', 'success');
            });
            
            video.addEventListener('loadedmetadata', () => {
                addLog('✓ 元数据已加载', 'success');
                addLog('  时长: ' + video.duration + ' 秒', 'info');
            });
            
            video.addEventListener('canplay', () => {
                addLog('✓ 可以播放', 'success');
            });
            
            video.addEventListener('play', () => {
                addLog('▶ 开始播放', 'success');
            });
            
            video.addEventListener('error', (e) => {
                addLog('✗ 播放错误: ' + e, 'error');
                if (video.error) {
                    addLog('错误代码: ' + video.error.code, 'error');
                    addLog('错误消息: ' + video.error.message, 'error');
                }
            });
            
            const audioContainer = document.getElementById('audioContainer');
            const audioElementDiv = document.getElementById('audioElement');
            audioElementDiv.innerHTML = '';
            audioElementDiv.appendChild(video);
            audioContainer.style.display = 'block';
            
            video.play().then(() => {
                addLog('✓ 播放成功', 'success');
            }).catch((error) => {
                addLog('✗ 播放失败: ' + error.message, 'error');
            });
            
            return video;
        }

        function testAudio(streamUrl, mimeType) {
            addLog('========== 音频播放测试 ==========', 'info');
            addLog('流链接: ' + streamUrl, 'info');
            addLog('MIME 类型: ' + mimeType, 'info');
            addLog('', 'info');
            
            showStatus('正在初始化...', 'info');
            
            // 首先尝试使用 Audio 元素
            addLog('尝试方法一：Audio 元素', 'info');
            audioInstance = testAudioWithAudioElement(streamUrl, mimeType);
            
            return audioInstance;
        }

        // 开始测试
        function startTest() {
            const streamUrl = document.getElementById('streamUrl').value.trim();
            const mimeType = document.getElementById('mimeType').value.trim();
            
            if (!streamUrl) {
                showStatus('请输入流链接 URL', 'error');
                addLog('✗ 错误: 流链接 URL 不能为空', 'error');
                return;
            }
            
            if (!mimeType) {
                showStatus('请输入 MIME 类型', 'error');
                addLog('✗ 错误: MIME 类型不能为空', 'error');
                return;
            }
            
            // 清空之前的音频元素
            const audioElementDiv = document.getElementById('audioElement');
            audioElementDiv.innerHTML = '';
            
            // 开始测试
            testAudio(streamUrl, mimeType);
        }

        // 页面加载完成
        window.addEventListener('load', () => {
            addLog('页面加载完成，准备就绪', 'success');
            addLog('请在输入框中填入流链接和 MIME 类型，然后点击"开始测试"', 'info');
        });

        // 导出到全局作用域
        window.testAudio = testAudio;
        window.testAudioWithAudioElement = testAudioWithAudioElement;
        window.testAudioWithVideoElement = testAudioWithVideoElement;
    </script>
</body>
</html>

